<?php

namespace xcxApi\modules\guest\controllers;

use Carbon\Carbon;
use common\components\fast_api\Controller;
use common\components\wtools\tools\Model;
use common\components\wtools\tools\Security;
use common\Tools;
use xcxApi\models\db\MpUsers;

class SiteController extends Controller
{
    /**
     * 小程序自动登录
     * @desc post
     * @param string $mp_code
     * @param string $mp_appid
     * @param string $user_info
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function actionMpLogin($mp_code, $mp_appid, $user_info)
    {
        if ($mp_appid !== \Yii::$app->xcx->appID) {
            return $this->apiError("appid错误");
        }
        $user_info = Tools::isJson($user_info);
        $encryptedData = $user_info['encryptedData'];
        $iv = $user_info['iv'];
        $signature = $user_info['signature'];
        $rawData = $user_info['rawData'];
        $res2 = \Yii::$app->xcx->decryptXcxData($mp_appid, $mp_code, $encryptedData, $iv, $signature, $rawData);
        $openid = $res2['openId'];
        $mpUser = MpUsers::find()
            ->andWhere(['mp_appid' => $mp_appid])
            ->andWhere(['mp_openid' => $openid])
            ->one();
        if (!$mpUser) {
            $mpUser = new MpUsers();
            $mpUser->mp_appid = $mp_appid;
            $mpUser->mp_openid = $openid;
            $mpUser->nickname = $res2['nickName'];
            $mpUser->avatar = $res2['avatarUrl'];
            $mpUser->gender = $res2['gender'];
            $mpUser->generateToken();
            if (!$mpUser->save()) {
                return $this->apiError(Model::getModelError($mpUser));
            }
        }
        return $this->apiSuccess([
            'jwtTokenArr' => $mpUser->generateJwtToken(),
            'mpUser' => MpUsers::getFilterShow($mpUser),
        ]);
    }
}